package com.aaa.sso.util;

import com.aaa.common.bo.User;
import com.aaa.sso.service.RemoteUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @fileName:MyRealm
 * @description:
 * @author:忆尘
 * @createTime:2020/11/13 19:46
 * @version:1.0.0
 */

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * AuthorizationInfo 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //获取收集到的用户名称
        String userName = (String)authenticationToken.getPrincipal();
        //根据用户名查询用户信息
        User user = remoteUserService.queryUserByParam(userName);
        //判断user是否为空 , 如果为空 , 说明账号不存在
        if(user == null){
            throw new AccountException();
        }
        //获取密码
        String password = user.getPassword();
        //获取盐值
        String salt = user.getSalt();
        //第一个user：用户信息 ， 第二个password：用户密码 ，第三个参数：ByteSource.Util.bytes(salt)加盐值，第四个参数this.getname ：本类名
        return new SimpleAuthenticationInfo(user,password,ByteSource.Util.bytes(salt),this.getName());
    }
}
